package demo05;

import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hp on 2020/2/26.
 */
public class Test01 {
    public static void main(String[] args) throws DocumentException {
        Object c1 = getBean("c1");
        System.out.println(c1);
    }
    public static Object getBean(String id) throws DocumentException {
        Element rootElement = new SAXReader().read("application-config.xml").getRootElement();
        List<Element> bean = rootElement.elements("bean");
        for (Element element : bean) {
            if (element.attributeValue("id").equals(id)){
                try {
                    Class<?> className = Class.forName(element.attributeValue("className"));
                    Object o = className.newInstance();
                    List<Element> properties = element.elements("properties");
                    HashMap<String, Object> map = new HashMap<>();
                    for (Element property : properties) {
                        map.put(property.attributeValue("name"),property.attributeValue("value"));
                    }
                    BeanUtils.populate(o,map);
                    return o;
                } catch (ClassNotFoundException e) {
                    return null;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
